<template>
  <div class="app-container">
    <!-- 班级筛选 -->
    <div class="filter-container">
      <div class="filter-item">
        <span class="label">起始日期：</span>
        <el-date-picker
          v-model="startDate"
          type="date"
          placeholder="选择起始日期"
          value-format="yyyy-MM-dd"
          :clearable="true"
          @clear="handleClear"
          @change="handleDateChange"
        />
      </div>

      <div class="filter-item">
        <span class="label">班级选择：</span>
        <el-checkbox-group v-model="selectedClasses" @change="handleClassChange">
          <el-checkbox
            v-for="cls in classOptions"
            :key="cls.value"
            :label="cls.value"
          >
            {{ cls.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <el-table :data="filteredTableData" border style="width: 100%">
      <!-- 日期列 -->
      <el-table-column prop="date" label="日期" width="120" />
      <!-- 日期列 -->
      <el-table-column prop="weekday" label="周几" width="120" />
      <!-- 动态生成班级列 -->
      <template v-for="cls in filteredClasses" >
        <el-table-column :label="cls.label">
          <el-table-column :prop="`${cls.value}.content`" label="授课内容" />

          <el-table-column label="授课老师" width="120" >
            <template slot-scope="scope" >
              <el-select
                v-show="scope.row[cls.value].content"
                v-model="scope.row[cls.value].teacher"
                placeholder="选择老师"
                clearable
                @change="(value) => handleTeacherAssign(value, scope.row, cls.value)">
                <el-option
                  v-for="teacher in teacherOptions"
                  :key="teacher.value"
                  :label="teacher.label"
                  :value="teacher.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
import {getTeachingPlanList,updateTeacherAssignment} from "@/api/teaching/teacher_scheduling"
// 创建延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

export default {

  name: "老师排班",
  data() {
    return {
      // 教师选项
      teacherOptions: [
      ],
      // 班级选项
      classOptions: [
      ],
      selectedClasses: [],
      lastSelectedClasses: null,
      startDate: '', // 将 dateRange 改为 startDate
      // 表格数据模型
      teachingPlanList: [
      ]
    };
  },
  mounted() {
    this.getTeachingPlanList();
  },
  computed: {
    // 过滤后的班级列表
    filteredClasses() {
      return this.classOptions.filter(cls =>
        this.selectedClasses.includes(cls.value)
      );
    },
    filteredTableData() {
      if (!this.startDate) {
        return this.teachingPlanList;
      }
      return this.teachingPlanList.filter(row => {
        return row.date >= this.startDate;
      });
    }
  },
  methods: {
    async getTeachingPlanList(){
      getTeachingPlanList().then(async response => {
        this.classOptions = response.data.classOptions;
        this.selectedClasses = response.data.classOptions.map(cls => cls.value);// 默认全选
        this.teacherOptions = response.data.teacherOptions;
        for (let i = 0; i < response.data.teachingPlanList.length; i++) {
          this.teachingPlanList.push(response.data.teachingPlanList[i]);
          await delay(150);
        }
      });
    },
    // 处理班级选择变化
    handleClassChange(value) {
      if (value.length === 0) {
        this.$message.warning('请至少选择一个班级');
        this.selectedClasses = this.lastSelectedClasses || ['java47'];
        return;
      }
      this.lastSelectedClasses = [...value];
    },

    // 检查教师冲突
    checkTeacherConflict(row, selectedTeacher, currentClass) {
      return this.selectedClasses.some(className => {
        if (className === currentClass) return false;
        return row[className]?.teacher === selectedTeacher;
      });
    },

    // 处理教师分配
    handleTeacherAssign(teacher, row, currentClass) {
      if (!teacher) {
        row[currentClass].teacher = teacher;
        return;
      }

      if (this.checkTeacherConflict(row, teacher, currentClass)) {
        this.$message.error(`${teacher}在该时间段已有其他课程安排`);
        row[currentClass].teacher = '';
        return;
      }

      row[currentClass].teacher = teacher;
      //同步到服务器
      updateTeacherAssignment(currentClass,teacher,row.date).then(resp=>{
        this.$message.success(`已分配${teacher}给${currentClass}`);
      }).catch(err=>{
        this.$message.error(err);
      })

    },

    // 处理日期变化
    handleDateChange(value) {
      this.startDate = value;
    },
    handleClear() {
      this.startDate = '';
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  margin-right: 10px;
}

.el-select {
  width: 100%;
}
</style>
